// src/containers/IdentityVerify/index.jsx - 修复后的身份验证组件
import { useState, useRef, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { Camera, CheckCircle, AlertCircle, RotateCcw, ArrowRight } from 'lucide-react'
import { api } from '../../utils/api'
import './style.css'

const IdentityVerify = () => {
  const { sessionId } = useParams()
  const navigate = useNavigate()
  const videoRef = useRef(null)
  const canvasRef = useRef(null)
  const [stream, setStream] = useState(null)
  const [verificationStep, setVerificationStep] = useState('init')
  const [capturedImage, setCapturedImage] = useState(null)
  const [verificationResult, setVerificationResult] = useState(null)
  const [error, setError] = useState('')
  const [isLoading, setIsLoading] = useState(false)

  useEffect(() => {
    // 检查是否有有效的sessionId
    if (!sessionId) {
      console.error('Session ID 不存在')
      setError('会话ID无效，请重新开始')
      return
    }

    // 初始化身份验证流程
    initializeVerification()

    return () => {
      // 清理摄像头资源
      if (stream) {
        console.log('清理摄像头资源')
        stream.getTracks().forEach(track => track.stop())
      }
    }
  }, [sessionId, stream])

  const initializeVerification = async () => {
    try {
      console.log('初始化身份验证，Session ID:', sessionId)
      // 调用后端验证身份接口，检查简历中是否有人脸
      const result = await api.verifyIdentity(sessionId)
      console.log('身份验证初始化结果:', result)
    } catch (err) {
      console.error('身份验证初始化失败:', err)
      setError('初始化失败：' + err.message)
      setVerificationStep('error')
    }
  }

  const startCamera = async () => {
    try {
      setIsLoading(true)
      setError('')
      console.log('开始启动摄像头...')
      
      // 检查浏览器是否支持摄像头
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        throw new Error('您的浏览器不支持摄像头功能')
      }
  
      const constraints = {
        video: {
          width: { ideal: 1280, min: 640 },
          height: { ideal: 720, min: 480 },
          facingMode: 'user'
        },
        audio: false
      }
      
      console.log('请求摄像头权限...')
      const mediaStream = await navigator.mediaDevices.getUserMedia(constraints)
      console.log('摄像头启动成功:', mediaStream)
      
      setStream(mediaStream)
      
      // 立即设置状态为camera，不等待video事件
      setVerificationStep('camera')
      
      // 等待下一个渲染周期再设置video
      setTimeout(() => {
        if (videoRef.current && mediaStream) {
          console.log('设置video srcObject...')
          videoRef.current.srcObject = mediaStream
          
          // 强制开始播放
          videoRef.current.play().catch(err => {
            console.log('自动播放可能被阻止，但摄像头已连接')
          })
        }
      }, 200)
      
    } catch (err) {
      console.error('摄像头启动失败:', err)
      let errorMessage = '无法访问摄像头'
      
      if (err.name === 'NotAllowedError') {
        errorMessage = '摄像头权限被拒绝，请在浏览器中允许摄像头访问'
      } else if (err.name === 'NotFoundError') {
        errorMessage = '未找到摄像头设备'
      } else if (err.name === 'NotReadableError') {
        errorMessage = '摄像头正在被其他应用程序使用'
      } else if (err.name === 'OverconstrainedError') {
        errorMessage = '摄像头不满足要求的约束条件'
      }
      
      setError(errorMessage)
      setVerificationStep('error')
    } finally {
      setIsLoading(false)
    }
  }

  const capturePhoto = () => {
    console.log('开始拍摄照片...')
    
    if (!videoRef.current || !canvasRef.current) {
      console.error('视频或画布元素不存在')
      setError('拍摄失败：视频元素未准备好')
      return
    }
    
    const video = videoRef.current
    const canvas = canvasRef.current
    const context = canvas.getContext('2d')
    
    console.log('视频状态:', {
      readyState: video.readyState,
      videoWidth: video.videoWidth,
      videoHeight: video.videoHeight,
      paused: video.paused
    })
    
    // 检查视频是否已加载
    if (video.readyState < 2) {
      setError('视频还未加载完成，请稍等')
      return
    }
    
    if (video.videoWidth === 0 || video.videoHeight === 0) {
      setError('无法获取视频尺寸，请重新启动摄像头')
      return
    }
    
    // 设置canvas尺寸
    canvas.width = video.videoWidth
    canvas.height = video.videoHeight
    
    console.log('Canvas尺寸设置为:', canvas.width, 'x', canvas.height)
    
    // 绘制当前视频帧到canvas
    context.drawImage(video, 0, 0, canvas.width, canvas.height)
    
    // 转换为base64图像
    const imageData = canvas.toDataURL('image/jpeg', 0.8)
    console.log('照片拍摄成功，数据长度:', imageData.length)
    console.log('图像数据前50个字符:', imageData.substring(0, 50))
    
    // 🔥 关键修复：确保设置状态
    setCapturedImage(imageData)
    
    // 🔥 关键修复：立即切换状态
    setVerificationStep('capture')
    
    console.log('✅ 照片拍摄完成，切换到确认页面')
  }

  const retakePhoto = () => {
    console.log('重新拍摄照片')
    setCapturedImage(null)
    setVerificationStep('camera')
  }

  const verifyIdentity = async () => {
    if (!capturedImage) {
      setError('没有照片可以验证')
      return
    }
    
    setIsLoading(true)
    setError('')
    console.log('开始身份验证...')
    
    try {
      console.log('发送验证请求，Session ID:', sessionId)
      console.log('图片数据长度:', capturedImage.length)
      
      const result = await api.captureFace(sessionId, capturedImage)
      console.log('验证结果:', result)
      
      setVerificationResult(result)
      
      if (result.verified) {
        console.log('身份验证成功')
        setVerificationStep('success')
        
        // 3秒后自动跳转到面试页面
        setTimeout(() => {
          console.log('跳转到面试页面')
          navigate(`/interview/${sessionId}`)
        }, 3000)
      } else {
        console.log('身份验证失败')
        setVerificationStep('error')
        setError(`身份验证失败：${result.message || '相似度过低'}`)
      }
      
    } catch (err) {
      console.error('身份验证错误:', err)
      setError(`验证过程出现错误：${err.message}`)
      setVerificationStep('error')
    } finally {
      setIsLoading(false)
    }
  }

  const resetVerification = () => {
    console.log('重置验证流程')
    setCapturedImage(null)
    setVerificationResult(null)
    setError('')
    setVerificationStep('init')
    
    // 停止当前摄像头流
    if (stream) {
      stream.getTracks().forEach(track => track.stop())
      setStream(null)
    }
  }

  const renderContent = () => {
    switch (verificationStep) {
      case 'init':
        return (
          <div className="verify-content">
            <div className="verify-icon">
              <Camera size={64} />
            </div>
            <h2>身份验证</h2>
            <p>我们需要验证您的身份以确保面试的真实性</p>
            <div className="verify-instructions">
              <h3>验证流程：</h3>
              <ol>
                <li>点击下方按钮启动摄像头</li>
                <li>正对摄像头，确保面部清晰可见</li>
                <li>拍摄照片进行身份比对</li>
                <li>验证通过后开始面试</li>
              </ol>
            </div>
            {error && (
              <div className="verify-error-message">
                <AlertCircle size={16} />
                {error}
              </div>
            )}
            <button 
              className="verify-action-btn verify-primary"
              onClick={startCamera}
              disabled={isLoading}
            >
              {isLoading ? (
                <div className="verify-loading-spinner"></div>
              ) : (
                <>
                  <Camera size={20} />
                  启动摄像头
                </>
              )}
            </button>
          </div>
        )

      case 'camera':
        return (
          <div className="verify-content">
            <h2>请正对摄像头</h2>
            <p>确保您的面部清晰可见，光线充足</p>
            <div className="verify-camera-container">
              <video
                ref={videoRef}
                autoPlay
                playsInline
                muted
                className="verify-camera-video"
                style={{
                  width: '100%',
                  maxWidth: '500px',
                  height: 'auto',
                  borderRadius: '8px',
                  border: '2px solid #e0e0e0',
                  backgroundColor: '#000', // 添加黑色背景
                  display: 'block' // 确保显示
                }}
                onCanPlay={() => {
                  console.log('视频可以播放了')
                }}
                onPlaying={() => {
                  console.log('视频正在播放')
                }}
                onError={(e) => {
                  console.error('视频错误:', e)
                }}
              />
              <div className="verify-face-outline"></div>
            </div>
            <div className="verify-camera-status">
              <p>📹 摄像头状态: {stream ? '✅ 已连接' : '❌ 未连接'}</p>
            </div>
            <div className="verify-camera-actions">
              <button 
                className="verify-action-btn verify-secondary"
                onClick={resetVerification}
              >
                重新开始
              </button>
              <button 
                className="verify-action-btn verify-primary"
                onClick={capturePhoto}
              >
                拍摄照片
              </button>
            </div>
          </div>
        )

      case 'capture':
        return (
          <div className="verify-content">
            <h2>确认照片</h2>
            <p>请确认照片清晰，然后进行身份验证</p>
            
            {/* 🔥 添加调试信息 */}
            <div style={{margin: '10px 0', fontSize: '12px', color: '#666'}}>
              调试信息: {capturedImage ? `照片已拍摄 (${capturedImage.length}字符)` : '照片未拍摄'}
            </div>
            
            <div className="verify-captured-photo">
              {capturedImage ? (
                <img 
                  src={capturedImage} 
                  alt="拍摄的照片"
                  style={{
                    maxWidth: '400px',
                    width: '100%',
                    height: 'auto',
                    borderRadius: '8px',
                    border: '2px solid #e0e0e0'
                  }}
                  onLoad={() => console.log('✅ 图片加载成功')}
                  onError={(e) => console.error('❌ 图片加载失败:', e)}
                />
              ) : (
                <div style={{
                  width: '400px',
                  height: '300px',
                  backgroundColor: '#f0f0f0',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  borderRadius: '8px'
                }}>
                  <p>照片加载中...</p>
                </div>
              )}
            </div>
            
            <div className="verify-capture-actions">
              <button 
                className="verify-action-btn verify-secondary"
                onClick={retakePhoto}
              >
                <RotateCcw size={20} />
                重新拍摄
              </button>
              <button 
                className="verify-action-btn verify-primary"
                onClick={verifyIdentity}
                disabled={isLoading || !capturedImage}
              >
                {isLoading ? (
                  <div className="verify-loading-spinner"></div>
                ) : (
                  <>
                    <CheckCircle size={20} />
                    开始验证
                  </>
                )}
              </button>
            </div>
          </div>
        )

      case 'success':
        return (
          <div className="verify-content verify-success">
            <div className="verify-success-icon">
              <CheckCircle size={64} />
            </div>
            <h2>验证成功！</h2>
            <p>身份验证通过，正在为您准备面试环境...</p>
            {verificationResult && (
              <div className="verify-verification-details">
                <div className="verify-similarity-score">
                  <span>相似度评分：</span>
                  <span className="verify-score">{(verificationResult.similarity_score * 100).toFixed(1)}%</span>
                </div>
              </div>
            )}
            <div className="verify-auto-redirect">
              <div className="verify-loading-dots">
                <span></span>
                <span></span>
                <span></span>
              </div>
              <p>3秒后自动进入面试...</p>
            </div>
            <button 
              className="verify-action-btn verify-primary"
              onClick={() => navigate(`/interview/${sessionId}`)}
            >
              <ArrowRight size={20} />
              立即开始面试
            </button>
          </div>
        )

      case 'error':
        return (
          <div className="verify-content verify-error">
            <div className="verify-error-icon">
              <AlertCircle size={64} />
            </div>
            <h2>验证失败</h2>
            <p className="verify-error-message">{error}</p>
            <div className="verify-error-suggestions">
              <h3>建议：</h3>
              <ul>
                <li>确保光线充足</li>
                <li>正对摄像头，面部完整可见</li>
                <li>与简历照片保持一致的表情</li>
                <li>避免遮挡面部</li>
                <li>检查浏览器摄像头权限</li>
                <li>使用HTTPS访问页面</li>
              </ul>
            </div>
            <button 
              className="verify-action-btn verify-primary"
              onClick={resetVerification}
            >
              重新验证
            </button>
          </div>
        )

      default:
        return null
    }
  }

  return (
    <div className="verify-identity-verify">
      <div className="verify-container">
        <div className="verify-progress-bar">
          <div className="verify-progress-steps">
            <div className={`verify-step ${['init', 'camera', 'capture', 'verify', 'success'].includes(verificationStep) ? 'verify-active' : ''}`}>1</div>
            <div className={`verify-step ${['capture', 'verify', 'success'].includes(verificationStep) ? 'verify-active' : ''}`}>2</div>
            <div className={`verify-step ${['success'].includes(verificationStep) ? 'verify-active' : ''}`}>3</div>
          </div>
          <div className="verify-progress-labels">
            <span>启动摄像头</span>
            <span>拍摄照片</span>
            <span>验证完成</span>
          </div>
        </div>
        
        {renderContent()}
        
        <canvas 
          ref={canvasRef} 
          style={{ display: 'none' }}
        />
      </div>
    </div>
  )
}

export default IdentityVerify